package com.mrx.xfriendship.converter;

import com.mrx.xfriendship.model.dto.AuthorDTO;
import com.mrx.xfriendship.model.po.CommentPO;
import com.mrx.xfriendship.model.po.UserPO;
import com.mrx.xfriendship.service.IMinioService;
import org.apache.commons.lang3.math.NumberUtils;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.MappingConstants;
import org.springframework.lang.Nullable;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Optional;

/**
 * 杂项 converter, 其它 converter 可以通过 {@link Mapper#uses()} 参数来调用本类<br/>
 * 备注: 后期发现这个设计真的挺拉的, MapStruct 还是不够智能
 * 为了防止 循环依赖, 本类的编写禁止依赖其它 SpringBean 类
 *
 * @author Mr.X
 * @since 2023-01-15 09:56
 */
@Mapper(componentModel = MappingConstants.ComponentModel.SPRING)
public abstract class OtherConverter {

    @Resource
    protected IMinioService minioService;

    public AuthorDTO toAuthorDTO(CommentPO po) {
        if (po == null) {
            po = new CommentPO();
            UserPO author = new UserPO();
            author.setName("暂无回复嗷");
            po.setAuthor(author);
        }
        return toAuthorDTO(po.getAuthor());
    }

    public String gender2String(Integer gender) {
        return Optional.ofNullable(gender).orElse(1).equals(1) ? "男" : "女";
    }

    public Integer string2Gender(String gender) {
        // 兼容 数字 和 字符
        if (NumberUtils.isDigits(gender)) {
            gender = gender2String(Integer.parseInt(gender));
        }
        return "男".equals(gender) ? 1 : 0;
    }

    @Nullable
    public LocalDateTime string2LocalDateTime(String time) {
        if (time == null) return null;
        LocalDate localDate = LocalDate.parse(time, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        return LocalDateTime.of(localDate, LocalTime.now());
    }

    public String toPreviewAvatar(String avatar) {
        return minioService.preview(avatar);
    }

    @Mapping(target = "avatar", expression = "java( po.getUserDetail() != null ? toPreviewAvatar(po.getUserDetail().getAvatar()): null )")
    @Mapping(target = "name", expression = "java( po.getName() )")
    public abstract AuthorDTO toAuthorDTO(UserPO po);

}
